import { RecordItem, useRecords } from 'hooks/useRecords';
import { useTags } from 'hooks/useTags';
import { ReactNode, useState } from 'react';
import styled from 'styled-components';
import Layout from '../components/Layout';
import { CategorySection } from './Money/CategorySection';
import day from 'dayjs';

const CategoryWrapper = styled.div`
  background: #ffffff;
`
const ITem = styled.div`
  background: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  line-height: 20px;
  padding: 10px 16px;
  > .note {
    color: #999;
    margin-right: auto;
    margin-left: 16px;
  }
`
const Header = styled.h3`
  font-size: 18px;
  line-height: 20px;
  padding: 10px 16px;
`

function Statistics() {
  const [category, setCategory] = useState<'-' | '+'>('-');
  const { records } = useRecords();
  const { getName } = useTags();

  const hash: { [K: string]: RecordItem[] } = {}; // {'2020-05-11': [item, item], '2020-05-10': [item, item], '2020-05-12': [item, item, item, item]}
  //收入支出记录分类
  const selectedRecords = records.filter(r => r.category === category);
  selectedRecords.forEach(r => {
    const key = day(r.createAt).format('YYYY年MM月DD日');
    if (!(key in hash)) {
      hash[key] = []
    }
    hash[key].push(r);
  })
  // 对hash进行排序 Object.entries作用是将key变成数组第一项 [["2021年06月24日", Array(4)]]
  const array = Object.entries(hash).sort((a, b) => {
    if (a[0] === b[0]) { return 0 }
    if (a[0] < b[0]) { return -1 }
    if (a[0] > b[0]) { return 1 }
    return 0
  })

  return (
    <Layout>
      <CategoryWrapper>
        <CategorySection value={category}
          onChange={value => setCategory(value)}></CategorySection>
      </CategoryWrapper>
      {array.map(([date, records]) =>
        <div>
          <Header>{date}</Header>
          <div>
            {records.map(r => {
              return (
                <ITem key={r.createAt}>
                  <div className="tags oneLine">
                    {r.tagIds
                      .map(tagId => <span key={tagId}>{getName(tagId)}</span>)
                      // [span, span, span]
                      // [span, ',' span, ',' span]
                      // []
                      .reduce((result, span, index, array)=> 
                        result.concat(index < array.length - 1 ? [span, '，'] : [span]), [] as ReactNode[])
                    }
                  </div>
                  {r.note && <div className="note">{r.note}</div>}
                  <div className="amount">￥{r.amount}</div>
                </ITem>
              )
            })}
          </div>
        </div>
      )}
    </Layout>
  );
}


export default Statistics;

